package com.ys.day30.p3Properties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.Format;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述: server and client 读取 properties配置文件来开启服务
 *
 * @author CodeYang
 * @version 2021/1/12 23:42
 */
public class P2ServerClientTest {

}

/**
 * 服务端 server
 */
class ServerSocket01 {
    public static void main(String[] args) {
        // socket.server.port 必须于配置文件一直,要不然就会找不到
        int prot = PropertiesUtils.getInt("socket.server.port");

        try (
                //注册服务
                ServerSocket serverSocket = new ServerSocket(prot);
                //监听端口
                Socket accept = serverSocket.accept();
                //获取输出流 用于给客户端发msg
                OutputStream outputStream = accept.getOutputStream();
                // 装饰流 以文本形式发送,此时使用字符流
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        ) {
            final LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-LL-dd HH:mm:ss");
            String format = formatter.format(now);
            // 把系统实际发送给客户端
            bufferedWriter.write(format.toString());
            // 换行结束标志
            bufferedWriter.newLine();
            bufferedWriter.flush();

        } catch (Exception e) {
            System.out.println("server - error");
            e.printStackTrace();
        }
    }
}

/**
 * 客户端 client
 */
class ClientSocket01 {

    public static void main(String[] args) {
        String address = PropertiesUtils.getString("socket.server.ip");
        int port = PropertiesUtils.getInt("socket.server.port");

        try (
                Socket socket = new Socket(address, port);
                // 获得输入流
                InputStream inputStream = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String data = br.readLine();
            System.out.println("now : "+data);

        } catch (Exception e) {
            System.out.println("client -- error");
            e.printStackTrace();
        }
    }

}
